import { routerRedux } from 'dva/router';
import {fakeAccountLogin} from '../services/api';
import { setAuthority } from '../utils/authority';
import { reloadAuthorized } from '../utils/Authorized';

export default {
  namespace: 'login',

  state: {
    status: undefined,
    code:"",
    data:{},
    message:'',
  },

  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(fakeAccountLogin, payload);
      if(response.code == 0){
        let userType = 'admin';
        switch(response.data.roleName){
          case '管理员':
            userType = 'admin';
            break;
          case '开发':
            userType ='开发';
            break;
          case '测试':
            userType='测试';
            break;
          case '产品':
            userType='产品';
            break;
        }

        yield put({
          type: 'changeLoginStatus',
          payload: { currentAuthority: userType},
        });
        reloadAuthorized();
        yield put(routerRedux.push('/quality/workbanch'));
      }
      else if(response.code == 20007 ){

          yield put({
            type: 'changeLoginStatus',
            payload:{data:response},
          });


      }



      
      // Login successfully
      // if (response.status === 'ok' && response.code === 0) {
      //   reloadAuthorized();
      // }
    },
    *logout(_, { put, select }) {
      try {
        // get location pathname
        const urlParams = new URL(window.location.href);
        const pathname = yield select(state => state.routing.location.pathname);
        // add the parameters in the url
        urlParams.searchParams.set('redirect', pathname);
        window.history.replaceState(null, 'login', urlParams.href);
      } finally {
        yield put({
          type: 'changeLoginStatus',
          payload: {
            status: false,
            currentAuthority: 'guest',
          },
        });
        reloadAuthorized();
        yield put(routerRedux.push('/user/login'));
      }
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.currentAuthority);
      return {
        ...state,

        ...payload
      };
    },
  },
};
